package org.geektimes.projects.user.web.listener;

import org.geekbang.projects.injection.ApplicationContext;
import org.geekbang.projects.injection.ApplicationContextCompleteAware;
import org.geekbang.projects.orm.MapperBuild;
import org.geektimes.projects.user.repository.DMLMapper;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
import java.sql.Connection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* 系统初始化类  
* @author : KangNing Hu
*/
public class SystemInitialization implements ApplicationContextCompleteAware {


	private static final Logger logger = Logger.getLogger(SystemInitialization.class.getName());




	@Override
	public void onComplete(ApplicationContext applicationContext) {
		//获取数据源
		try {
			//初始化应用上下文
			DataSource dataSource = applicationContext.getBean("jdbc/UserPlatformDB");
			//初始化orm
			MapperBuild.initDataSource(dataSource);
			logger.log(Level.INFO ,"orm初始化完成");
			try (final Connection connection = dataSource.getConnection();){
				logger.log(Level.INFO ,"JNDI加载数据源成功");
			}catch (Exception e){
				throw new IllegalStateException("JNDI加载数据源失败");
			}
			//初始化数据表
			DMLMapper  dmlMapper = applicationContext.getBean("mapper/dmlMapper");
			try {
				dmlMapper.dropTable();
			}catch (Exception e){
				logger.log(Level.WARNING ,"数据表不存在");
			}
			try {
				dmlMapper.createTable();
			}catch (Exception e){
				logger.log(Level.WARNING ,"数据表已存在");
			}

			//初始化jmx
			logger.log(Level.INFO ,"jmx初始化完成");
			logger.log(Level.INFO ,"初始化数据表完成");
		}catch (Exception e){
			throw new IllegalStateException(e);
		}
	}
}
